<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%@ taglib prefix="jwr"  uri="http://jawr.net/tags-el" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>


<jwr:script src="/bundles/knockout.js"/>

<div id="tabContent" style="min-height: 500px;">

	<input type="hidden" id="categoryId" name="categoryId" value="${category.id}"/>
	
	<c:url value="/rest/admin/category/assignmenus/save?" var="saveMenuCategoryUrl" />
	<c:url value="/rest/admin/category/assignmenus/search?" var="searchMenuCategoryUrl" />
	<c:url value="/rest/admin/category/menu/list?" var="getCategoryMenuListUrl" />

	<script type="text/javascript">
	
	var saveMenuCategoryUrl = "${saveMenuCategoryUrl}";
	var searchMenuCategoryUrl = "${searchMenuCategoryUrl}";
	var getCategoryMenuListUrl = "${getCategoryMenuListUrl}";
	// OnDomReady
	dojo.addOnLoad(function() {
		
				// Declare View Model - This object wraps all menu/behavior for service area page.
				function CategoryMenuViewModel() {
					// Under some conditions, 'this' reference gets hijacked, store a local copy
					var self = this;

					// Selected Menu, County, Zip options.  Anytime a user adds or deletes items, these are the arrays to get updated (UI will auto update)
					self.menus = ko.observableArray([]);
					

					//************************************************
					// Menu Related Functions (add, get, remove)
					//************************************************
					self.addMenu = function(menuId) {
						
						if(!self.isMenuDuplicate(menuId)) {
							// getMenu would be replaced with server side xhr call (xhr call should return the same json response as mocked out getMenu call)
							self.updateMenuDetails(menuId);
							
						}
						eleById('menu-input').value = '';
						eleById('menu-input').focus();
						
					};
					
					//Check menu is already added in the list or not
					self.isMenuDuplicate = function(menuId) {
						var isDuplicate = false;
						ko.utils.arrayForEach(self.menus(), function(entry) {
							if (entry.menu.id == menuId+"".toUpperCase()) {
								isDuplicate = true;								
							}
						});
						return isDuplicate;
					};
					
					// Replace me with an xhr call to save/retrieve Menu CategoryEntryObject
					self.updateMenuDetails = function(menuId) {
						YAHOO.util.Connect.asyncRequest("GET", saveMenuCategoryUrl+"menuId="+menuId +"&categoryId="+eleById('categoryId').value, {
							cache : false,
							success : function(o) {
								var response = (o.getResponseHeader['Content-Type'].indexOf('json') > -1);
								if (response) {
									var responseText = YAHOO.lang.JSON.parse(o.responseText);
									if (responseText.isSuccess) {
										self.menus.push(responseText.categoryMenuEntry);
										self.menus.sort(function(a, b) {
											return a.menu.name > b.menu.name;
										});
									}								
								}
							},
							failure : function(o) {
								displayErrorMessage("Not able to submit Laboratory details for approval at this time, please try again later.", "lab-approval-status-message");
							}
						});
					};

					self.removeMenu = function() {
						// Add call here to make xhr to delete menu then remove from array if success
						self.menus.remove(this);
					};
					
					self.pushAllMenu = function(categoryArea){
						ko.utils.arrayPushAll(self.menus(), categoryArea);
						self.menus.sort(function(a, b) {
							return a.menu.name > b.menu.name;
						});
					};
					
				};
				// Create new instance of ModelView and bind to it
				var cavm = new CategoryMenuViewModel();
				ko.applyBindings(cavm);
				
				function addMenu(id) {
					// This method would be called once user selected option from type ahead
					cavm.addMenu(id);
				}
				
				/**
				Menu Auto Complete
				**/
				// Function used to format results of AutoComplete  
				var autoCompleteMenuResultFormatter = function(oResultData, sQuery, sResultMatch) {
					if (!oResultData.menu) {
						// If no results found, just display description (this is where "no results found" message is stored).
						return oResultData.shortDesc;
					}
					var name = oResultData.menu.name;
					return name ;
				};
				var menuSearchDataSource = new YAHOO.util.XHRDataSource("category/menu/quickSearch",
						{
							responseSchema : {
								resultsList : "results.resultList",
								fields : [ "menu" ],
								metaFields : {
									totalRecords : "results.totalResultsFound"
								}

							}
						});

				var menuSearchAutoComplete = new YAHOO.widget.AutoComplete("menu-input", "menu-container",
						menuSearchDataSource, {
							minQueryLength : 2,
							resultTypeList : false,
							forceSelection : true,
							formatResult : autoCompleteMenuResultFormatter
						});

				menuSearchAutoComplete.generateRequest = function(sQuery) {
					return "?query=" + sQuery + "&searchType=menu";
				};

				menuSearchAutoComplete.itemSelectEvent.subscribe(function(sType, aArgs) {
					//Spring.remoting.getResource("${flowExecutionUrl}", {_eventId:"addTest", testNumber:aArgs[2].productNum});
					if (aArgs[2].menu.id && aArgs[2].menu.id != "") {
						addMenu(aArgs[2].menu.id);
					}
					// Clear out input value
					aArgs[0].getInputEl().value = '';
				});

				menuSearchAutoComplete.doBeforeLoadData = function(sQuery,	oResponse, oPayload) {
					if (!oResponse || !oResponse.meta) {
						return false;
					}
					var totalRecords = oResponse.meta.totalRecords;
					var records = oResponse.results;
					if (records.length == 0) {
						// Add 'No Results Found' dummy message
						records.push({code : "", shortDesc : "No results found for query '"	+ unescape(sQuery) + "'"});
						this.setHeader("");
					} else {
						this.setHeader("Showing " + records.length + " of "	+ totalRecords);
					}
					return true;
				};
				
				
				//Load existing menus if availables
				YAHOO.util.Connect.asyncRequest("GET", getCategoryMenuListUrl+"categoryId="+eleById('categoryId').value, {
					cache : false,
					success : function(o) {
						var response = (o.getResponseHeader['Content-Type'].indexOf('json') > -1);
						if (response) {
							var responseText = YAHOO.lang.JSON.parse(o.responseText);
							
							if (responseText.menuList.length > 0) {
								cavm.pushAllMenu( responseText.menuList);
							}
							
						}
					},
					failure : function(o) {
						displayErrorMessage("Not able to submit Laboratory details for approval at this time, please try again later.", "lab-approval-status-message");
					}
				});
			});
	</script>
	
	
		<div style="padding: 20px 0px 10px 0px;">
			<div id="btnReturnToCategoryList" style="text-align: right;float: right;">
				<input class="btnClass" onclick="returnToCatgoryList();"
				     id="btnReturnToCategoryList" name="btnReturnToCategoryList" type="button" value="Return to Category List"/>
			</div>
			<div class="font-header">Selected Category : ${category.name} </div>
			<div style="clear: both;"></div>
		</div>
		<div class="instruction-sub-text" style="margin: 0px 0px">
			Assign Menu Item to Category.
		</div>
		
		<div style="float: left;margin-top:5px;">
			<div>
				<div class="arrow-bullet" style="float: left;margin-top: 8px;">&nbsp;</div>
				<div style="float: left;width: 105px;">Assign Menus</div>
				<div style="width: 668px;border-bottom: 1px solid #55648f;margin-top:-10px;float: left;">&nbsp;</div>
			</div>			
		</div>
		
		<div style="padding: 5px 0px" class="instruction-sub-text">The
			Category can be defined by selecting one or more Menus. To
			Add/Select a Menu, enter at least the first 2 characters of the Name
			into the field below.</div>
		<br>
		<div id="shadeContainer" style="width: 100%;">
			<div class="shaded-form-background"	style="clear: both;">
				<div style="margin: 10px 0px 10px 40px; width: 325px;">
					<div class="red-form-background" style="clear: both;">
						<div class="search-add-label" style="float: left;width: 70px;">Add Next</div>
						<div style="margin-top: 0px; width: 210px; float: left;">
							<div class="form-fieldtop"><div class="form-fieldb1"></div><div class="form-fieldb2"></div></div>
							<div class="form-fieldcontent" style="height: 28px; clear: both;">
								<input type="text" name="menu-input" id="menu-input"
									style="width: 203px;" title="Enter Menu code or Name">
								<div id="menu-container" style="width: 500px"></div>
							</div>
							<div class="form-fieldtop"><div class="form-fieldb2"></div><div class="form-fieldb1"></div></div>
						</div>
						<div style="clear: both;"></div>
					</div>
				</div>
				<div style="clear: both;"></div>
			</div>
			<div style="padding: 5px 0px" class="instruction-sub-text">Selected Menu Items will be added in below.</div>
			<div class="shaded-form-background"	style="margin: 5px 0px;padding:15px;  clear: both;">
				<div class="paperboxcontent" style="padding: 10px 10px;border-width: 0px;">
					<div id="menuList" data-bind="foreach: menus">
						<div class="font-field-detail" style="float: left; width: 100%; margin-right:10px; border: 1px solid black;margin-bottom: 4px;">
							<span style="padding-left: 5px;float: left;" data-bind="text: menu.name"></span> 
							<a href="javascript:void(0)" data-bind="click:$parent.removeMenu">
								<span style="float: right;padding-right: 5px;color: red;">X</span></a>
						</div>						
					</div>
					<div style="clear: both;"></div>
				</div>
				<div style="clear: both;"></div>
			</div>
			<div style="clear: both;"></div>
		</div>
	
	
</div>

<script type="text/javascript">
	
</script>